package com.wxw.BaseLibrary.http.soap;

import android.util.Xml;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by david on 2016/5/11.
 */
public class GetSoapExecutor implements SoapExecutor {
    private static GetSoapExecutor _INSTANCE;

    private GetSoapExecutor() {

    }

    public static GetSoapExecutor getInstance() {
        if (_INSTANCE == null) {
            _INSTANCE = new GetSoapExecutor();
        }
        return _INSTANCE;
    }

    @Override
    public <T> SoapResponse<T> executeRequest(Request<T> request) {
        String url = request.url();
        Map<String, Object> params = request.getParams();
        if (params !=null && params.size()>0) {
            StringBuffer paramBuffer = new StringBuffer();
            Set<String> keys = params.keySet();
            for (String key : keys) {
                try {
                    paramBuffer.append("&");
                    paramBuffer.append(URLEncoder.encode(key, "utf-8"));
                    paramBuffer.append("=");
                    paramBuffer.append(URLEncoder.encode(params.get(key).toString(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException("Encoding utf-8 format is not supported by the system");
                }
            }
            if (paramBuffer.length() > 0) {
                paramBuffer.deleteCharAt(0);
                url += (url.endsWith("?")?"":"?")+paramBuffer.toString();

            }
        }
        HttpGet request_get = new HttpGet(url);

        if (request.getHeaders() != null && request.getHeaders().size()>0) {
            Set<String> keys = request.getHeaders().keySet();
            for (String key : keys) {
                request_get.setHeader(key, request.getHeaders().get(key));
            }
        }
        if (!"".equals(request.getAccept())) {
            request_get.setHeader("Accept", request.getAccept());
        }
        if (!"".equals(request.getContentType())) {
            request_get.setHeader("Content-type", request.getContentType());
        }
        BasicHttpParams basicHttpParams = new BasicHttpParams();
        ConnManagerParams.setTimeout(basicHttpParams, 10000);
        HttpConnectionParams.setConnectionTimeout(basicHttpParams, 20000);
        HttpConnectionParams.setSoTimeout(basicHttpParams, 20000);
        HttpConnectionParams.setSocketBufferSize(basicHttpParams,8*1024);
        HttpClientParams.setRedirecting(basicHttpParams, true);
        long startTime = System.currentTimeMillis();
        Exception exception = null;
        int StatusCode = 0;
        DefaultHttpClient httpClient = new DefaultHttpClient(basicHttpParams);
        byte[] body = null;
        T result = null;

        try {
            HttpResponse response = httpClient.execute(request_get);
            StatusCode = response.getStatusLine().getStatusCode();
            if (StatusCode == HttpURLConnection.HTTP_OK) {
                body = SoapResponse.readResponseBody(response.getEntity().getContent());
                result = request.parseResponse(url, body);
            } else {
                body = response.getEntity().toString().getBytes("utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            exception = e;
        }
        long endTime = System.currentTimeMillis();

        return new SoapResponse(url, RequestMethod.GET, request.getHeaders(),StatusCode, body, result,
                request.getTag(),endTime-startTime, exception);
    }
}
